<template>
  <div class="qrcode-generator">
    <el-row :gutter="20">
      <!-- 输入和配置区域 -->
      <el-col :xs="24" :sm="24" :md="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <el-icon color="#E6A23C">
                <picture-rounded />
              </el-icon>
              <span class="ml-2">二维码生成器</span>
            </div>
          </template>

          <el-form>
            <el-form-item>
              <el-input
                v-model="content"
                type="textarea"
                :rows="4"
                :maxlength="500"
                show-word-limit
                placeholder="输入文本或链接"
                @input="generateQR"
              />
            </el-form-item>

            <el-divider>样式配置</el-divider>

            <el-row :gutter="20">
              <el-col :xs="24" :sm="12">
                <el-form-item label="二维码大小">
                  <el-select v-model="size" class="w-full" @change="generateQR">
                    <el-option
                      v-for="option in sizeOptions"
                      :key="option.value"
                      :label="option.text"
                      :value="option.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12">
                <el-form-item label="边距大小">
                  <el-select v-model="margin" class="w-full" @change="generateQR">
                    <el-option
                      v-for="option in marginOptions"
                      :key="option.value"
                      :label="option.text"
                      :value="option.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12">
                <el-form-item label="前景色">
                  <el-color-picker v-model="color" show-alpha @change="generateQR" />
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="12">
                <el-form-item label="背景色">
                  <el-color-picker v-model="background" show-alpha @change="generateQR" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="Logo">
              <el-upload
                class="upload-area"
                accept="image/*"
                :auto-upload="false"
                :show-file-list="false"
                @change="handleLogoUpload"
              >
                <template #trigger>
                  <el-button type="primary">
                    <el-icon class="mr-2">
                      <upload />
                    </el-icon>
                    上传Logo
                  </el-button>
                </template>
                <template #tip>
                  <div class="el-upload__tip">可选，支持jpg、png等图片格式</div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 预览和下载区域 -->
      <el-col :xs="24" :sm="24" :md="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <el-icon color="#67C23A">
                <view />
              </el-icon>
              <span class="ml-2">预览</span>
            </div>
          </template>

          <div class="preview-container">
            <div class="qr-preview">
              <qrcode-vue
                v-if="content"
                ref="qrcode"
                :value="content"
                :size="size"
                :margin="margin"
                :foreground="color"
                :background="background"
                level="H"
                render-as="canvas"
              />
              <img v-if="logoUrl" :src="logoUrl" class="qr-logo" :style="logoStyle" />
            </div>

            <div class="action-buttons">
              <el-button type="primary" :disabled="!content" @click="downloadQR('png')">
                <el-icon class="mr-2">
                  <download />
                </el-icon>
                下载PNG
              </el-button>
              <el-button type="info" :disabled="!content" @click="downloadQR('svg')">
                <el-icon class="mr-2">
                  <download />
                </el-icon>
                下载SVG
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import QrcodeVue from 'qrcode.vue';
import { PictureRounded, View, Upload, Download } from '@element-plus/icons-vue';

const content = ref('');
const size = ref(200);
const margin = ref(2);
const color = ref('#000000');
const background = ref('#FFFFFF');
const logoFile = ref(null);
const logoUrl = ref(null);

const sizeOptions = [
  {
    text: '小 (150px)',
    value: 150
  },
  {
    text: '中 (200px)',
    value: 200
  },
  {
    text: '大 (300px)',
    value: 300
  },
  {
    text: '超大 (400px)',
    value: 400
  }
];

const marginOptions = [
  {
    text: '无边距',
    value: 0
  },
  {
    text: '窄边距',
    value: 1
  },
  {
    text: '标准边距',
    value: 2
  },
  {
    text: '宽边距',
    value: 4
  }
];

const logoStyle = computed(() => {
  const logoSize = size.value * 0.2; // Logo大小为二维码的20%
  return {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    width: `${logoSize}px`,
    height: `${logoSize}px`,
    borderRadius: '50%',
    padding: '2px',
    background: '#fff'
  };
});

const generateQR = () => {
  if (!content.value) return;
  // 二维码生成是响应式的，不需要额外处理
};

const handleLogoUpload = async file => {
  try {
    const reader = new FileReader();
    reader.onload = e => {
      logoUrl.value = e.target.result;
    };
    reader.readAsDataURL(file.raw);
  } catch (error) {
    ElMessage.error('Logo加载失败');
  }
};

const downloadQR = async format => {
  if (!content.value) {
    ElMessage.warning('请先输入内容');
    return;
  }

  try {
    const canvas = document.querySelector('canvas');
    const dataUrl = canvas.toDataURL(`image/${format}`);

    const link = document.createElement('a');
    link.download = `qrcode.${format}`;
    link.href = dataUrl;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    ElMessage.success('下载成功');
  } catch (error) {
    ElMessage.error('下载失败');
  }
};
</script>

<style scoped>
.qrcode-generator {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.ml-2 {
  margin-left: 0.5rem;
}

.mr-2 {
  margin-right: 0.5rem;
}

.w-full {
  width: 100%;
}

.preview-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.qr-preview {
  position: relative;
  display: inline-block;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 2px dashed var(--el-border-color);
  border-radius: 6px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}
</style>
